class UsersController < ApplicationController
  before_filter :find_user, :only => [:edit, :show, :destroy, :update]
  before_filter :authorize, :except => [:index, :new, :create] # overrides :authorize from application_controller
  before_filter :restricted_access, :except => [:index, :update, :destroy, :create, :show, :new, :edit]
  before_filter :allow_mods, :only => [:update, :destroy, :create]
  
  # GET /users
  # GET /users.xml
  def index
    @users = User.paginate :page => params[:page], :order => 'created_at DESC', :per_page => 10

    respond_to do |format|
      format.html # index.html.erb
#      format.xml  { render :xml => @users }
    end
  end
  
  # GET /users/1
  # GET /users/1.xml
  def show
    respond_to do |format|
      format.html # show.html.erb
#      format.xml  { render :xml => @user }
    end
  end
  
  # GET /users/new
  # GET /users/new.xml
  def new
    if logged_in? # LOGGED IN
      unless current_user.access == 1
        flash[:notice] = "You are already logged in.  Please log out in order to register a new account." 
        redirect_to :controller => "home"
      end
    end 
    
    @user = User.new
    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end
  
  # GET /users/1/edit
  def edit
    if @user.name==Tools.get_system_user.name 
      return(redirect_to :back) unless current_user==@user 
    end
  end
  
  # POST /users
  # POST /users.xml
  def create
    @user = User.new(params[:user])
    
    params[:access] = 0 unless logged_in? && is_admin?
    
    respond_to do |format|
      if @user.save
        if logged_in?
          flash[:notice] = 'User account was successfully created.'
          format.html { redirect_to(@user) }
          format.xml  { render :xml => @user, :status => :created, :location => @user }
        else
          user = User.authenticate(params[:user][:name], params[:user][:password]) 
          if user
            session[:user_id] = user.id
            uri = session[:original_uri] 
            session[:original_uri] = nil
          end
          format.html { redirect_to :controller => "home" }
          format.xml  { render :xml => @user, :status => :created, :location => @user }
        end
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # PUT /users/1
  # PUT /users/1.xml
  def update
    @dont_change_name = (@user.name==Tools.get_system_user.name ? true:false)
    if @dont_change_name
      return (redirect_to :back) unless @user.name==params[:user][:name]
    end
    if @user.access == 0 # NORMAL USER
      update_user('Your details were successfully updated.', :controller => "home")
    else # ADMIN USER
      update_user('User was successfully updated.', :controller => "users")
    end
    @user.after_destroy
    @user = nil
  end
  
  # DELETE /users/1
  # DELETE /users/1.xml
  def destroy
    if @user.name == "Shims Library"
      flash[:notice] = "This user account cannot be deleted."
      return(redirect_to :back)
    end
    
    begin 
      session[:user_id] = nil if @user==current_user # log user out 
      @user.destroy
      flash[:notice] = "#{@user.name.capitalize}'s account has been deleted." 
    rescue Exception => e 
      flash[:notice] = e.message 
    end 
    
    respond_to do |format|
      if logged_in?
        format.html { redirect_to(users_url) }
      else
        format.html { redirect_to :controller => "home" }
      end
      format.xml  { head :ok }
    end
  end

  protected
  
  def authorize 
    unless logged_in? # NOT LOGGED IN
      session[:original_uri] = request.request_uri
      flash[:notice] = "Please log in" 
      redirect_to :controller => "home", :action => "login"
    end 
  end
  
  def allow_mods
    if @user
      unless is_admin?
        unless current_user.id == @user.id # if trying to access other profiles
          flash[:notice] = "You do not have suffiecient priviledges to view this area" 
          redirect_to :controller => "home"
        end
      end
    end
  end
  
  def restricted_access
    unless is_admin?
      flash[:notice] = "You do not have suffiecient priviledges to view this area" 
      redirect_to :controller => "home"
    end
  end

  private
  
  def find_user
    begin
      @user = User.find(params[:id])
    rescue
      flash[:notice] = "No user could be found with ID #{params[:id]}"
      redirect_to :controller => "users"
    end
  end
  
  def update_user(msg, redirect)
    respond_to do |format|
      params[:access] = 0 unless logged_in? && is_admin?
      if @user.update_attributes(params[:user])
        flash[:notice] = msg
        format.html { redirect_to redirect }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end   
  end
end
